//
//  VideoCompleteVC.m
//  SelfDriving
//
//  Created by apple on 16/2/3.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "VideoCompleteVC.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "ReleaseMainVC.h"
#import "MemberRoamingCell.h"
#import "YSHYClipViewController.h"

@interface VideoCompleteVC ()<UICollectionViewDataSource,UICollectionViewDelegate,ClipViewControllerDelegate>
{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
    
    NSData *videoData;
    NSMutableArray *imgdata;
    
    //xhw9月27号改：
    BOOL issend;
    BOOL isSynchronous;
    NSString *title;
}
@property (weak, nonatomic) IBOutlet UICollectionView *videoCollection;
@property (weak, nonatomic) IBOutlet UICollectionView *videoView;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIView *playerView;
@property (nonatomic,strong) NSMutableArray *videoList;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (weak, nonatomic) IBOutlet UIView *shareBgView;
@property (weak, nonatomic) IBOutlet UIImageView *sendImage;
@property (weak, nonatomic) IBOutlet UIImageView *synchronousImage;

@end
@implementation VideoCompleteVC
- (void)viewDidLoad {
    [AppDelegate shareDelegate].dtcoles = YES;
    [super viewDidLoad];
    imgdata = [NSMutableArray array];
    _videoList = [NSMutableArray array];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self create];
    
    //xhw2018-1-25改bug15400:快拍视频默认选中“发送给附近的人”和“同步到我的动态”
    issend = YES;
    isSynchronous = YES;
    
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
- (void)create
{
    if (_playerLayer) {
        [_playerLayer removeFromSuperlayer];
    }
    if (_videoUrl) {
        _playItem = [AVPlayerItem playerItemWithURL:_videoUrl];
        _player = [AVPlayer playerWithPlayerItem:_playItem];
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        _playerLayer.frame = _playerView.frame;
        if(_Fullscreen){
            UIView *bgview = [[UIView alloc]initWithFrame:CGRectMake(0, 54, SCRE_WIDTH, SCRE_HEIGHT)];
            bgview.backgroundColor = [UIColor blackColor];
            [self.view addSubview:bgview];
            _playBtn.frame = CGRectMake(SCRE_WIDTH/2-20, SCRE_HEIGHT/2-20, 40, 40);
        }else{
            _playBtn.frame = CGRectMake(_playerView.frame.size.width/2-20, _playerView.frame.size.height/2-20, 40, 40);
        }
        _playerView.hidden = YES;
        //    [_playerLayer addSublayer:_playBtn.layer];
        _playBtn.hidden = NO;
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
        [self.view.layer addSublayer:_playerLayer];
    }
    
    [self.view bringSubviewToFront:_playBtn];
    [self.view bringSubviewToFront:_backBtn];
    [self.view bringSubviewToFront:_submitBtn];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.view bringSubviewToFront:_shareBgView];
}
- (IBAction)playAction:(UIButton *)sender {
    [_player play];
    sender.hidden = YES;
}

-(void)playbackFinished:(NSNotification *)notification
{
    [_player seekToTime:CMTimeMake(0, 1)];
    _playBtn.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_player pause];
    [_player seekToTime:CMTimeMake(0, 1)];
    _playBtn.hidden = NO;
}
#pragma mark 保存压缩
- (NSURL *)compressedURL
{
    return [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"compressed.mp4"]]];
}

- (CGFloat)fileSize:(NSURL *)path
{
    return [[NSData dataWithContentsOfURL:path] length]/1024.00 /1024.00;
}

- (void)saveVideo:(NSURL *)outputFileURL
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
                                completionBlock:^(NSURL *assetURL, NSError *error) {
                                    if (error) {
                                        NSLog(@"保存视频失败:%@",error);
                                    } else {
                                        NSLog(@"保存视频到相册成功");
                                    }
                                }];
}

- (IBAction)backAction:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}
- (IBAction)nextAction:(UIButton *)sender {

    if (self.commitVideo) {
        self.commitVideo(self.videoUrl, [NSData dataWithContentsOfURL:self.videoUrl]);
    } else {
        //选择封面
//        YSHYClipViewController * clipView = [[YSHYClipViewController alloc]initWithImage:[self getVideoPreViewImage:self.videoUrl]];
//        clipView.delegate = self;
//        clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
//        clipView.radius = SCRE_WIDTH/2.0;   //设置 裁剪框的半径  默认120
//        [self presentViewController:clipView animated:YES completion:nil];
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        if (title) {
            [dic setObject:title forKey:@"title"];
        }
        else {
            [dic setObject:@"" forKey:@"title"];
        }
        
        //注意:NSMutableDictionary中不能保存bool值
        if (issend) {
            [dic setObject:@1 forKey:@"isSendNearBy"];
        }
        else {
            [dic setObject:@0 forKey:@"isSendNearBy"];
        }
        if (isSynchronous) {
            [dic setObject:@1 forKey:@"isSynchronizeToDynamic"];
        }
        else {
            [dic setObject:@0 forKey:@"isSynchronizeToDynamic"];
        }
        [self finlishCompleteVideo:[self getVideoPreViewImage:[self videoUrl]] param:dic];
    }
}
- (IBAction)editTitleAction:(UIButton *)sender {
    
    UIAlertController * alertCtrl = [UIAlertController alertControllerWithTitle:@"标题" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        //xhw改bug14931
        if (title) {
            textField.text = title;
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField * titleTextField = alertCtrl.textFields.firstObject;
        title = titleTextField.text;
    }];
    [alertCtrl addAction:cancelAction];
    [alertCtrl addAction:okAction];
    [self presentViewController:alertCtrl animated:YES completion:nil];
}
- (IBAction)sendSynchronousAction:(UIButton *)sender {
    if (sender.tag == 1001) {//发送给附近的人
        if (!issend) {
            self.sendImage.image = [UIImage imageNamed:@"选择---已选.png"];
        }else {
            self.sendImage.image = [UIImage imageNamed:@"选择---未选.png"];
        }
        issend = !issend;
    }else if (sender.tag == 1002) {//同步动态
        if (!isSynchronous) {
            self.synchronousImage.image = [UIImage imageNamed:@"选择---已选.png"];
        }else {
            self.synchronousImage.image = [UIImage imageNamed:@"选择---未选.png"];
        }
        isSynchronous = !isSynchronous;
    }

}

#pragma mark - ClipViewControllerDelegate-已选截图-上传服务器
-(void)finlishCompleteVideo:(UIImage *)editImage param:(NSDictionary* )paramter
{
    if (self.videoUrl == nil) {
        NSLog(@"文件读取错误");
    }else{
        if (self.commitVideo) {
            self.commitVideo(self.videoUrl, [NSData dataWithContentsOfURL:self.videoUrl]);
        } else {
            //快拍发送到服务器
            NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
            [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];

            NSString *title = [paramter objectForKey:@"title"];
            if (title) {
                [dic setObject:title forKey:@"title"];
            }
            NSNumber *isSendNearBy = [paramter objectForKey:@"isSendNearBy"];
            
            [dic setObject:isSendNearBy forKey:@"tonearyby"];
            
            NSNumber *isSynchronizeToDynamic = [paramter objectForKey:@"isSynchronizeToDynamic"];
            
            [dic setObject:isSynchronizeToDynamic forKey:@"todynamic"];
            
            videoData = [NSData dataWithContentsOfURL:self.videoUrl];
            NSMutableArray *imgData =[[NSMutableArray alloc]init];
            NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
            [dici setObject:@"video" forKey:@"key"];
            [dici setObject:videoData forKey:@"value"];
            [imgData addObject:dici];
            NSMutableDictionary *dic2 = [[NSMutableDictionary alloc]init];
            [dic2 setObject:@"img" forKey:@"key"];
            [dic2 setObject:UIImageJPEGRepresentation(editImage, 0.00001) forKey:@"value"];
//            [imgdata addObject:dic2];
            [imgData addObject:dic2];
            
            NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_kuaipaiurl postParems:dic data:imgData];
            [[NSURLConnection connectionWithRequest:request delegate:self] start];
        }
    }
}
/*
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage param:(NSDictionary* )paramter
{
    if (self.videoUrl == nil) {
        NSLog(@"文件读取错误");
    }else{
        if (self.commitVideo) {
            self.commitVideo(self.videoUrl, [NSData dataWithContentsOfURL:self.videoUrl]);
        } else {
            //快拍发送到服务器
            NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
            [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uid"];
            [dic setObject:@"" forKey:@"title"];
            [dic setObject:@1 forKey:@"tonearyby"];
            [dic setObject:@1 forKey:@"todynamic"];
 
            videoData = [NSData dataWithContentsOfURL:self.videoUrl];
            NSMutableArray *imgData =[[NSMutableArray alloc]init];
            NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
            [dici setObject:@"video" forKey:@"key"];
            [dici setObject:videoData forKey:@"value"];
            [imgData addObject:dici];
            NSMutableDictionary *dic2 = [[NSMutableDictionary alloc]init];
            [dic2 setObject:@"img" forKey:@"key"];
            [dic2 setObject:UIImageJPEGRepresentation(editImage, 0.00001) forKey:@"value"];
            [imgdata addObject:dic2];
            
            NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:publish_kuaipaiurl postParems:dic data:imgData];
            [[NSURLConnection connectionWithRequest:request delegate:self] start];
        }
    }
}
 */


- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    float progres = progress/total;
    [SVProgressHUD showProgress:progres status:@"发布中..."];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    if(code == 0){
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        //创建通知
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNotification *notification = [NSNotification notificationWithName:@"public" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil userInfo:nil];
            
            //xhw12月28号加:同步到动态之后，在我的资料详细里面的动态也应该刷新
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDynamicDataOfMyInformation" object:nil];
        });
        //把最前面的视图控制器dismiss掉
        UIViewController *parentVC = self.presentingViewController;
        UIViewController *bottomVC;
        while (parentVC) {
            bottomVC = parentVC;
            parentVC = parentVC.presentingViewController;
        }
        
        [bottomVC dismissViewControllerAnimated:YES completion:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)sectio{
    if(_data.count==0){
        return 0;
    }
    return _data.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MemberRoamingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MemberRoamingCell" forIndexPath:indexPath];
    
    if(_data.count==0){
        return cell;
    }
    NSMutableDictionary *dic = [_data objectAtIndex:indexPath.row];
    //    NSURL *url = [[result defaultRepresentation] url];
    //    UIImage *image = [UIImage imageWithCGImage:[result thumbnail]];
    cell.img.image = [dic objectForKey:@"img"];
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCRE_WIDTH-40)/4, (SCRE_WIDTH-40)/4);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic = [_data objectAtIndex:indexPath.row];
    _videoUrl = [dic objectForKey:@"url"];
    [self create];
}

// 获取视频第一帧
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}
@end
